import { combineReducers } from 'redux';
import {
  AUTH_SUCCESS,
  ERR_MES,
  RECEIVE_USER,
  RESET_USER,
  RECEIVE_USER_LIST,
  RECEIVE_MESSAGE_LIST,
  RECEIVE_NEW_MESSAGE,
  READ_MESSAGE
} from './action-types'

import { getRedirectTo } from '../utils'


/* 
  user状态
*/
const initUser = {
  username: '', // 用户名
  type: '', // 用户类型
  message: '', //错误提示信息
  redirectTo: ''
}
function user(state = initUser, action) {
  switch (action.type) {
    case AUTH_SUCCESS:
      const { type, header } = action.data
      return {...action.data, redirectTo: getRedirectTo(type, header)}
    case ERR_MES:
        return {...state, message: action.data}
    case RECEIVE_USER:
      return action.data
    case RESET_USER:
      return {...initUser, message: action.data}
    default:
      return state
  }
}


/* 
  user-list状态
*/
const initUserList = []
function userList(state = initUserList, action) {
  switch (action.type) {
    case RECEIVE_USER_LIST:
      return action.data // 返回获取到的用户列表
    default:
      return state
  }
}


/* 
  chat聊天状态
 */
const initChat = {
  users: {},  // 所有与当前用户有聊天记录的用户信息
  chatMsgs: [],  // 所有与当前用户相关的消息数组
  unreadCount: 0  // 未读消息数量
}
function chat(state = initChat, action) {
  switch (action.type) {
    case RECEIVE_MESSAGE_LIST: // action.data = {users, chatMsgs, userId}
      const {users, chatMsgs, userId} = action.data
      let unreadCount = 0
      // 计算未读数量
      chatMsgs.forEach(msg => {
        if (msg.to === userId && !msg.read) {
          unreadCount += 1
        }
      })
      return {users, chatMsgs, unreadCount}

    case RECEIVE_NEW_MESSAGE: //收到新消息 action.data = {message, userId}
      const newState = JSON.parse(JSON.stringify(state))
      const {message} = action.data
      const user_Id = action.data.userId
      if (message.to === user_Id && !message.read) {
        newState.unreadCount += 1
      }
      newState.chatMsgs.push(action.data.message)
      return newState
    
    case READ_MESSAGE: // 修改未读未已读 action.data = {count, from, userId}
      const {count, from} = action.data
      const userid = action.data.userId
      const newstate = JSON.parse(JSON.stringify(state))
      newstate.chatMsgs.forEach((msg) => {
        if (msg.from === from && msg.to === userid) {
          msg.read = true
        }
      })
      newstate.unreadCount -= count
      return newstate

    default:
      return state
  }
}



const reducer = combineReducers({
  user,
  userList,
  chat
});

export default reducer;